<template>
  <div class="apiAccess-box">
    <el-form :model="selectForm" :inline="true">
      <el-form-item label="时间">
        <el-date-picker class="el-date-picker"
          :clearable="false"
          size="small"
          v-model="selectForm.date"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="平台">
        <el-select v-model="selectForm.platform" clearable placeholder="请选择" size="small" style="margin-right: 10px;">
          <el-option v-for="item in selectForm.platforms" :key="item.label" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="版本">
        <el-select v-model="selectForm.version" clearable placeholder="请选择" size="small" style="margin-right: 10px;">
          <el-option v-for="item in selectForm.versions" :key="item.label" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="地区">
        <el-select v-model="selectForm.area" clearable placeholder="请选择" size="small" style="margin-right: 10px;">
          <el-option v-for="item in selectForm.areas" :key="item.label" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="运营商">
        <el-select v-model="selectForm.operator" clearable placeholder="请选择" size="small" style="margin-right: 10px;">
          <el-option v-for="item in selectForm.operators" :key="item.label" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="small" :loading="false" @click="getApiAccessData()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-col :span="24">
        <div id="pie-echart" style="width:100%; height:420px;" v-loading="isPieLoading"></div>
      </el-col>
      <el-col :span="24">
        <div id="bar-echart" style="width:100%; height:350px;" v-loading="isBarLoading"></div>
      </el-col>
      <el-col :span="24">
        <el-table stripe :data="detailTableData" v-loading="isDetailLoading">
          <el-table-column property="id" label="返回码" width="120"></el-table-column>
          <el-table-column property="title" label="类别">
            <template slot-scope="scope">
              <span v-html="scope.row.title"></span>
            </template>
          </el-table-column>
          <el-table-column property="requestSum" label="请求总数" width="120"></el-table-column>
          <el-table-column property="delayAvg" label="请求延时" width="120"></el-table-column>
          <el-table-column property="ratio" label="百分比" width="120"></el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import moment from 'moment'
import echarts from 'echarts'

export default {
  data () {
    return {
      selectForm: {
        date: moment().format('YYYY-MM-DD'),
        platform: '',
        platforms: [
          {label: '全部', value: ''}
        ],
        version: '',
        versions: [
          {label: '全部', value: ''}
        ],
        area: '',
        areas: [
          {label: '全部', value: ''}
        ],
        operator: '',
        operators: [
          {label: '全部', value: ''}
        ]
      },
      echarts: {
        pie: '',
        bar: ''
      },
      isPieLoading: false,
      isBarLoading: false,
      isDetailLoading: false,
      isPieNodata: false,
      isBarNodata: false,
      pieTitle: '某站点用户访问来源',
      barTitle: '某站点用户访问来源',
      pieXData: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎'],
      barXdata: ['1月22', '1月23', '1月24', '1月25', '1月26', '1月27', '1月28'],
      pieEchartData: [
        {value: 335, name: '直接访问'},
        {value: 310, name: '邮件营销'},
        {value: 234, name: '联盟广告'},
        {value: 135, name: '视频广告'},
        {value: 1548, name: '搜索引擎'}
      ],
      barEchartData: [5, 15, 8, 12, 25, 35, 13],
      detailTableData: []
    }
  },
  activated () {
    this.getQueryConditionData()
    this.getApiAccessData()
    // this.initChart()
  },
  methods: {
    // 获取所有查询条件的数据
    getQueryConditionData () {
      var vm = this
      vm.$http({
        url: vm.$http.adornUrl('/distribute/getcondition'),
        methods: 'get'
      }).then(({data}) => {
        if (data && data.code === 0) {
          let cites = data.data.city
          for (let city in cites) {
            vm.selectForm.areas.push({label: cites[city], value: city})
          }

          let operators = data.data.operator
          for (let operator in operators) {
            vm.selectForm.operators.push({label: operators[operator], value: operator})
          }

          let plats = data.data.plat
          for (let platform in plats) {
            vm.selectForm.platforms.push({label: plats[platform], value: platform})
          }

          let versions = data.data.version
          for (let version in versions) {
            vm.selectForm.versions.push({label: versions[version], value: version})
          }
        }
      })
    },
    getApiAccessData () {
      var vm = this
      vm.isPieLoading = true
      vm.isBarLoading = true
      vm.isDetailLoading = true
      vm.$http({
        url: vm.$http.adornUrl('/distribute/list'),
        methods: 'get',
        params: vm.$http.adornParams({
          'date': vm.selectForm.date,
          'version': vm.selectForm.version,
          'plat': vm.selectForm.platform,
          'city': vm.selectForm.area,
          'operator': vm.selectForm.operator
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          // 饼图数据
          let pieData = data.data.pieChart
          vm.pieTitle = pieData.title
          vm.pieXData = []
          vm.pieEchartData = []
          if (pieData.items.length > 0) {
            vm.isPieNodata = false
            vm.pieXData = pieData.items.map(item => {
              return item.title.replace(/<[^>]+>/g, '') // 正则表达式是为了匹配html标签
            })
            vm.pieEchartData = pieData.items.map(item => {
              return {
                name: item.title.replace(/<[^>]+>/g, ''), // 正则表达式是为了匹配html标签
                value: parseInt(item.number)
              }
            })
          } else {
            vm.isPieNodata = true
          }

          // 条状图数据
          let barData = data.data.barChart
          vm.barTitle = barData.title
          vm.barXdata = []
          vm.barEchartData = []
          if (barData.xAxis.length > 0) {
            for (let x in barData.xAxis) {
              vm.barXdata.push(barData.xAxis[x])
            }
          }
          if (barData.values.length > 0) {
            vm.isBarNodata = false
            for (let r in barData.values) {
              vm.barEchartData.push(parseInt(barData.values[r]).toFixed(2))
            }
          } else {
            vm.isBarNodata = true
          }

          vm.initChart()

          // 表格数据
          let detailData = data.data.distributeDetails
          vm.detailTableData = detailData.items.map(item => {
            return {
              id: item.id,
              title: item.title,
              requestSum: parseInt(item.requestSum),
              delayAvg: parseInt(item.delayAvg),
              ratio: (item.ratio * 100).toFixed(3) + '%'
            }
          })
          vm.isDetailLoading = false
        }
      })
    },
    initChart () {
      var vm = this
      vm.echarts.pie = echarts.init(document.getElementById('pie-echart'))
      vm.echarts.bar = echarts.init(document.getElementById('bar-echart'))
      vm.renderPieEchart()
      vm.renderBarEchart()
      window.addEventListener('resize', () => {
        vm.echarts.pie.resize()
        vm.echarts.var.resize()
      })
    },
    renderPieEchart () {
      var vm = this
      let option = {
        title: [
          {
            text: vm.pieTitle,
            x: 'left',
            textStyle: {
              fontSize: 14
            }
          }, {
            show: vm.isPieNodata,
            text: '暂无数据',
            top: '42%',
            left: 'center',
            textStyle: {
              fontSize: 14
            }
          }
        ],
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          itemWidth: 15,
          itemHeight: 15,
          itemGap: 2,
          padding: 2,
          bottom: 0,
          data: vm.pieXData
        },
        color: ['#345BA0', '#00A65A', '#3F8B65', '#61B34A', '#6FA1CC', '#34A0D9', '#00C0EF', '#39CCCC', '#3191D8', '#378AAC', '#F39C12', '#FF851B'],
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        roam: false, // 鼠标缩放及平移
        focusNodeAdjacency: false, // 是否在鼠标移到节点上的时候突出显示节点以及节点的边和邻接节点
        series: [
          {
            name: '请求量',
            type: 'pie',
            startAngle: 90,
            radius: '55%',
            center: ['50%', '53%'],
            data: vm.pieEchartData,
            itemStyle: {
              normal: {
                borderWidth: 1,
                borderColor: '#fff'
              },
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              normal: {
                show: true,
                formatter: '{b} : {d}%'
              }
            }
          }
        ]
      }
      vm.echarts.pie.setOption(option)
      vm.isPieLoading = false
    },
    renderBarEchart () {
      var vm = this
      let option = {
        title: [
          {
            text: vm.barTitle,
            x: 'left',
            textStyle: {
              fontSize: 14
            }
          }, {
            show: vm.isBarNodata,
            text: '暂无数据',
            top: '42%',
            left: 'center',
            textStyle: {
              fontSize: 14
            }
          }
        ],
        tooltip: {
          trigger: 'item',
          // formatter: '{b}<br/>{a} : {c}'
          formatter: function (params) {
            return params.seriesName + '<br/>' + params.marker + ' ' + params.name + ' : ' + params.value
          }
        },
        legend: {
          data: ['code'],
          textStyle: {
            color: '#333'
          },
          bottom: 0
        },
        color: ['#00A65A'],
        grid: {
          left: '5%',
          right: '5%',
          top: 70
        },
        xAxis: [
          {
            type: 'category',
            data: vm.barXdata,
            axisPointer: {
              type: 'shadow'
            },
            axisLabel: {
              show: false
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '时间(ms)',
            nameGap: 20,
            nameTextStyle: {
              padding: [0, 8, 0, 0]
            },
            axisLabel: {
              formatter: function (params) {
                return params / 1000 + 'k'
              },
              color: '#333'
            },
            axisTick: {
              show: false
            },
            axisLine: {
              show: false
            }
          }
        ],
        series: [
          {
            name: 'code',
            type: 'bar',
            barWidth: 60,
            label: {
              normal: {
                show: false,
                position: 'top'
              }
            },
            data: vm.barEchartData
          }
        ]
      }
      vm.echarts.bar.setOption(option)
      vm.isBarLoading = false
    }
  }
}
</script>
<style scoped>
.apiAccess-box .el-form{
  text-align: right;
  margin-bottom: 15px;
  border-bottom: 1px solid #eee;
}
.apiAccess-box .el-date-picker{
  width: 170px;
}
.apiAccess-box .el-select{
  width: 110px;
}
.apiAccess-box .el-button{
  padding: 8px 15px;
  font-size: 14px;
}
.apiAccess-box .el-col{
  margin-bottom: 20px;
}
</style>
